package leetcode.easy;

import java.util.Stack;

public class $20_IsBracketsValid {
    public boolean isValid(String s) {
        if (s.length() == 0 || s.length() % 2 == 1)
            return false;
        if (!isLeft(s.charAt(0)))
            return false;
        Stack<Character> stack = new Stack<>();
        for (int index = 0;index < s.length();index++) {
            if (isLeft(s.charAt(index))) {
                stack.push(s.charAt(index));
            } else {
                if (!stack.empty() && match(stack.peek(), s.charAt(index))) {
                    stack.pop();
                } else {
                    if (index < s.length() - 1)
                        return false;
                    break;
                }
            }
        }
        if (stack.empty())
            return true;
        else
            return false;
    }

    public boolean match(char left, char right){
        if (left == '(' && right == ')')
            return true;
        else if (left == '{' && right == '}')
            return true;
        else if (left == '[' && right == ']')
            return true;
        else
            return false;
    }

    public boolean isLeft(char inputChar) {
        return inputChar == '{' || inputChar == '[' || inputChar == '(';
    }
}
